package com.weipai.springboot.module.service.impl;

import com.weipai.springboot.enums.RetCode;
import com.weipai.springboot.model.GoodsOption;
import com.weipai.springboot.model.ProductCategory;
import com.weipai.springboot.model.ProductProperty;
import com.weipai.springboot.model.PropertyOption;
import com.weipai.springboot.model.api.PageResult;
import com.weipai.springboot.model.api.Response;
import com.weipai.springboot.module.dao.*;
import com.weipai.springboot.module.mapper.ProductCategoryMapper;
import com.weipai.springboot.module.mapper.ProductPropertyMapper;
import com.weipai.springboot.module.mapper.PropertyOptionMapper;
import com.weipai.springboot.module.service.ProductPropertyService;
import net.sf.json.JSONArray;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.text.html.Option;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 曹朋飞
 * @Date: 2018/08/21 16:51
 */
@Service
public class ProductPropertyServiceImpl implements ProductPropertyService {

    private static final Logger log = LoggerFactory.getLogger(ProductPropertyServiceImpl.class);
    @Autowired
    ProductPropertyDao productPropertyDao;
    @Autowired
    PropertyOptionDao propertyOptionDao;
    @Autowired
    GoodsOptionDao goodsOptionDao;
    @Autowired
    ProductCategoryDao productCategoryDao;
    @Autowired
    private GoodsDao goodsDao;

    private final static String SPLIT = ",";
    private final static String SPLIT2 = ",|，";

    //保存货品类别属性
    @Override
    public Response save(ProductProperty productProperty, String propertyOptionValue) {
        Response response = new Response();
        for (String s : propertyOptionValue.split(SPLIT)) {
            PropertyOption propertyOption = new PropertyOption();
            propertyOption.setPropertyId(productProperty.getPropertyId());
            propertyOption.setOptionValue(s);
            propertyOptionDao.insert(propertyOption);
        }
        if (1 == productPropertyDao.insert(productProperty)) {
            response.setCode(RetCode.SUCCESS);
        } else {
            log.debug("保存货品类别属性:{}", productProperty.getPropertyName());
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //修改
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Response update(String id, String propertyName, String[] propertyOptionValue) {
        Response response = new Response();
        int size01 = propertyOptionValue.length;
        List<String> oldId = new ArrayList<>();
        List<String> newId = new ArrayList<>();
        List<String> oldName = new ArrayList<>();
        List<Integer> oldSort = new ArrayList<>();
        List<String> newName = new ArrayList<>();
        List<Integer> newSort = new ArrayList<>();
        for (int y = 0; y < size01; y++) {
            String[] idAndValue = propertyOptionValue[y].split(":");
            if (idAndValue[0].equals("-1")) {
                newId.add(idAndValue[0]);
                newName.add(idAndValue[1]);
                newSort.add(Integer.parseInt(idAndValue[2]));
            } else {
                oldId.add(idAndValue[0]);
                oldName.add(idAndValue[1]);
                oldSort.add(Integer.parseInt(idAndValue[2]));
            }
        }
        //得到数据库中该属性一共有多少个属性选项
        List<Map<String, Object>> map = propertyOptionDao.getOptionAmountByPropertyId(id);
        int size02 = map.size();
        if (null != map && size02 > 0) {
            List<String> list = new ArrayList<>();
            for (int i = 0; i < size02; i++) {
                list.add(map.get(i).get("id").toString());
            }
            if (list.size() > oldId.size()) {
                //有删除选项值的操作
                list.removeAll(oldId);
                for (int r = 0; r < list.size(); r++) {
                    Integer amount = goodsOptionDao.getGoodsOptionByOptionId(list.get(r));
                    if (amount > 0) {
                        response.put("code", 500);
                        response.put("msg", "该选项值有关联商品，请解除关联商品再进行删除操作");
                        return response;
                    } else {
                        propertyOptionDao.deleteById(list.get(r));
                    }
                }
                //修改
                int size04 = oldName.size();
                for (int y = 0; y < size04; y++) {
                    if (propertyOptionDao.updateOptionName(oldId.get(y), oldName.get(y), oldSort.get(y)) != 1) {
                        response.setCode(RetCode.REQUEST_ERROR);
                        return response;
                    }
                }
            }else {
                int size04 = oldName.size();
                for (int y = 0; y < size04; y++) {
                    if (propertyOptionDao.updateOptionName(oldId.get(y), oldName.get(y), oldSort.get(y)) != 1) {
                        response.setCode(RetCode.REQUEST_ERROR);
                        return response;
                    }
                }
            }
        }
        //新增
        int size03 = newName.size();
        for (int y = 0; y < size03; y++) {
            PropertyOption propertyOption = new PropertyOption();
            propertyOption.setPropertyId(id);
            propertyOption.setOptionValue(newName.get(y));
            propertyOption.setOptionSort(newSort.get(y));
            if (propertyOptionDao.insert(propertyOption) != 1) {
                response.setCode(RetCode.REQUEST_ERROR);
                return response;
            }
        }
        productPropertyDao.updatePropertyName(id, propertyName);
        response.setCode(RetCode.SUCCESS);
        return response;
    }

    //查询详情
    @Override
    public Response getProductPropertyById(String id) {
        Response response = new Response();
        ProductProperty property = productPropertyDao.selectByPrimaryKey(id);
        if (null != property) {
            List<PropertyOption> optionList = propertyOptionDao.getOptionByPropertyId(id);
            int size = optionList.size();
            response.setCode(RetCode.SUCCESS);
            if (size > 0) {
                List<String> valueList = new ArrayList<>();
                for (int i = 0; i < size; i++) {
                    valueList.add(optionList.get(i).getOptionValue());
                }
                response.put("valueList", valueList);
            }
            response.put("property", property);
        } else {
            log.debug("请求属性详情为空");
            response.setCode(RetCode.NO_DATA);
        }
        return response;
    }

    //删除
    @Override
    public Response deleteById(String id) {
        Response response = new Response();
        if (!judge(id)) {
            response.put("code", 500);
            response.put("msg", "选项值有关联商品，请解除关联商品再进行删除操作");
            return response;
        }
        if (1 == productPropertyDao.deleteByPrimaryKey(id)) {
            productPropertyDao.deleteOption(id);
            response.setCode(RetCode.SUCCESS);
        } else {
            log.debug("删除属性失败:{}", id);
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //批量删除
    @Override
    public Response batchDeleteById(String[] id) {
        Response response = new Response();
        for (int i = 0; i < id.length; i++) {
            if (!judge(id[i])) {
                response.put("code", 500);
                response.put("msg", "选项值有关联商品，请解除关联商品再进行删除操作");
                return response;
            }
        }
        for (int i = 0; i < id.length; i++) {
            if (1 == productPropertyDao.deleteByPrimaryKey(id[i])) {
                productPropertyDao.deleteOption(id[i]);
            } else {
                response.setCode(RetCode.REQUEST_ERROR);
                log.debug("删除属性失败:{}", id[i]);
                return response;
            }
        }
        response.setCode(RetCode.SUCCESS);
        return response;
    }

    //更改状态
    @Override
    public Response changeStatus(String id, Integer status) {
        Response response = new Response();
        if (-1 == status) {
            if (!judge(id)) {
                response.setCode(RetCode.NO_DATA);
                response.put("msg", "选项值有关联商品，请解除关联商品再进行删除操作");
                return response;
            }
        }
        if (1 == productPropertyDao.updateStatus(id, status)) {
            response.setCode(RetCode.SUCCESS);
        } else {
            log.debug("修改属性失败:{}", id);
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //分页查询
    @Override
    public Response selectAllByProductCategoryId(Integer page, Integer size, String draw, String productCategoryId) {
        Integer start = (page - 1) * size;
        List<ProductProperty> propertyList = productPropertyDao.selectAllByProductCategoryId(start, size, productCategoryId);
        int size01 = propertyList.size();
        if (size01 > 0) {
            for (int i = 0; i < size01; i++) {
                List<PropertyOption> optionList = propertyOptionDao.getOptionByPropertyId(propertyList.get(i).getPropertyId()); //获取属性列表值
                int size02 = optionList.size();
                if (size02 > 0) {
                    StringBuffer sf = new StringBuffer();  //属性值
                    StringBuffer sf2 = new StringBuffer();  //optin_id  值
                    for (int j = 0; j < size02; j++) {
                        sf.append(optionList.get(j).getOptionValue()).append(SPLIT);
                        sf2.append(optionList.get(j).getOptionId()).append(SPLIT);
                    }
                    // "updateTime": "黑色,红色"
                    propertyList.get(i).setUpdateTime(sf.substring(0, sf.length() - 1).toString());
                    //属性值 id
                    propertyList.get(i).setCreateTime(sf2.substring(0, sf2.length() - 1).toString());
                    if (size02 > 0) {
                        StringBuffer sf3 = new StringBuffer();
                        for (int j = 0; j < size02; j++) {
                            sf3.append(optionList.get(j).getOptionValue()).append(SPLIT);
                        }
                        propertyList.get(i).setUpdateTime(sf.substring(0, sf3.length() - 1).toString());
                    }
                }
            }
        }
        Integer totalNum = productPropertyDao.selectAllByProductCategoryIdAmount(productCategoryId);
        PageResult<ProductProperty> pageList = new PageResult<>(propertyList, page, size, totalNum, draw);
        Response response = new Response();
        response.setCode(RetCode.SUCCESS);
        ProductCategory productCategory = productCategoryDao.getProductCategoryById(productCategoryId);
        if (null != productCategory) {
            response.put("productCategoryName", productCategory.getProductCategoryName());
        } else {
            response.put("productCategoryName", null);
        }
        response.put("pageList", pageList);
        return response;
    }

    //通过第三级的商品分类获取到属性与属性选项
    @Override
    public Response getOptionByProductCategoryId(String id, String SpuNumber, String type) {
        Response response = new Response();
        List<Object> list = productPropertyDao.getOptionByPropertyCategoryId(id, SpuNumber, type);
        if (list.size() > 0) {
            response.setCode(RetCode.SUCCESS);
            response.put("list", list);
        } else {
            response.setCode(RetCode.NO_DATA);
        }
        return response;
    }

    //通过产品的id来查询出此商品下面的所有属性和属性选项
    @Override
    public Response getOptionByProductId(String productId, String spuNumber, String type) {
        Response response = new Response();
        List<Object> list = productPropertyDao.getOptionByProductId(productId, spuNumber, type);
        if (list.size() > 0) {
            response.setCode(RetCode.SUCCESS);
            response.put("list", list);
        } else {
            response.setCode(RetCode.NO_DATA);
        }
        return response;
    }

    /**
     * 判断该属性是否关联商品
     *
     * @param id
     * @return
     */
    private boolean judge(String id) {
        //得到数据库中该属性一共有多少个属性选项
        List<Map<String, Object>> map = propertyOptionDao.getOptionAmountByPropertyId(id);
        int size02 = map.size();
        if (null != map && size02 > 0) {
            List<String> list = new ArrayList<>();
            for (int i = 0; i < size02; i++) {
                list.add(map.get(i).get("id").toString());
            }
            if (list.size() > 0) {
                for (int r = 0; r < list.size(); r++) {
                    Integer amount = goodsOptionDao.getGoodsOptionByOptionId(list.get(r));
                    if (amount > 0) {
                        return false;
                    }
                }
            }
        }
        return true;
    }
}
